# coding:utf-8
# user
from os import pipe
from sqlalchemy.sql.elements import Null
from myblog.model.admin import Admin
from myblog import db
import json
import myblog
from flask import request, jsonify, session
from flask import Blueprint, render_template, redirect
adminController = Blueprint('user', __name__)


@adminController.route('/regist', methods=['POST'])
def regist():
    username = request.form['username']  # 用户名
    password = request.form['password']  # 密码
    if username and password:
        if db.session.query(Admin).filter(Admin.username == username).first():
            return jsonify({'data': {}, 'meta': {"code": 403, "msg": "用户名已存在！！！"}})
        else:
            db.session.add(Admin(username=username, password=password))
            db.session.commit()
            return jsonify({'data': {}, 'meta': {"code": 200, "msg": "恭喜，注册成功！"}})
    else:
        return jsonify({'data': {}, 'meta': {"code": 403, "msg": "用户名/密码，请检查！！！"}})


@adminController.route('/login', methods=['POST'])
def login():
    print(22222222222222222222222222222222222222222222222222222222222222)

    data = json.loads(request.get_data(as_text=True))
    username = data['username']  # 用户名
    password = data['password']  # 密码
    print(username)
    print(password)
    if username and password:
        rs = db.session.query(Admin).filter(
            Admin.username == username and Admin.password == password).first()
        print(333333333333333333333333333)
        print(rs)
        if rs:
            userInfo = {'iconSrc': rs.iconSrc, 'username': username}
            session['username'] = username
            print(session.get('username'))
            return jsonify({'data': userInfo, 'meta': {"code": 200, "msg": "恭喜，登錄成功！"}})
        else:
            return jsonify({'data': {}, 'meta': {"code": 403, "msg": "用户名/密码，请检查！！！"}})


@adminController.route('/updatepassword/<user>', methods=['POST'])
def updatepassword(user):
    if session.get('username') == user:
        password = request.form['password']  # 用户名
        admin = Admin.query.filter(Admin.username == user).first()
        admin.password = password
        db.session.commit()
        return jsonify({'data': {}, 'meta': {"code": 200, "msg": "修改密码成功！"}})
    else:
        return jsonify({'data': {}, 'meta': {"code": 403, "msg": "不是用户权限"}})


@adminController.route('/show')
def show():
    return 'user_show'
